package gorm

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"gorm.io/driver/mysql"
	"log"
	"os"
	"time"
)

var (
	DB *gorm.DB
)

func init(){
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "read_only:Readonly@132132@tcp(10.7.235.231:3305)/ids_persistence?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second, // 慢 SQL 阈值
			LogLevel:                  logger.Info, // 日志级别
			IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  true,        // 禁用彩色打印
		},
	)
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 该配置去掉自动在user表加s
		},
		Logger: newLogger,
	})
	// 连接池 设置
	sqlDB, _ := DB.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(60 * time.Second)

	if err != nil {
		panic(err)
	}
}

type BaseModel struct {
	ID int32 `gorm:"primarykey"`
	CreateAt time.Time `gorm:"column:add_time"`
	UpdateAt time.Time `gorm:"column:update_time"`
	DeleteAt gorm.DeletedAt
	IsDeleted bool
}

type User struct {
	BaseModel
	Mobile string `gorm:"index:idx_mobile;unique;type:varchar(11);not null "`
	PassWord string `gorm:"type:varchar(100);not null"`
	NickName string `gorm:"type:varchar(20)"`
	Birthday *time.Time `gorm:"type:datetime"`
	Gender string `gorm:"column:gender;default:male;type:varchar(6)"`
	Role int `gorm:"column:role;default:1;type:int comment '1 indicates a common user, and 2 indicates an administrator'"`
}

func main () {
	// 获取用户列表
	var datas []User
	result := DB.Find(&datas)
	if result.Error != nil {
		fmt.Println(result.Error)
	}
	fmt.Println(datas)
}
